
// pages/login/login.js
const app = getApp()
const defaultAvatarUrl = '/images/avatar.png'

Page({
  data: {
    userInfo: {
      avatarUrl: defaultAvatarUrl,
      nickName: ''
    },
    hasUserInfo: false,
    canIUseGetUserProfile: false
  },

  onLoad() {
    if (wx.getUserProfile) {
      this.setData({
        canIUseGetUserProfile: true
      })
    }
  },

  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    this.setData({
      'userInfo.avatarUrl': avatarUrl
    })
  },

  onInputChange(e) {
    this.setData({
      'userInfo.nickName': e.detail.value
    })
  },

  getUserProfile() {
    if (!this.data.userInfo.nickName) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    // 显示授权确认框
    wx.showModal({
      title: '温馨提示',
      content: '需要获取您的个人信息以完善会员资料',
      success: (modalRes) => {
        if (modalRes.confirm) {
          wx.getUserProfile({
            desc: '用于完善会员资料',
            lang: 'zh_CN',
            success: (res) => {
              console.log('getUserProfile success:', res)
              // 保留用户选择的头像和输入的昵称
              const userInfo = {
                ...res.userInfo,
                avatarUrl: this.data.userInfo.avatarUrl,
                nickName: this.data.userInfo.nickName
              }
              this.setData({
                userInfo,
                hasUserInfo: true
              })
              this.handleLogin(userInfo)
            },
            fail: (err) => {
              console.error('获取用户信息失败:', err)
              wx.showToast({
                title: '获取用户信息失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: '您取消了授权',
            icon: 'none'
          })
        }
      }
    })
  },

  getUserInfo(e) {
    if (!this.data.userInfo.nickName) {
      wx.showToast({
        title: '请输入昵称',
        icon: 'none'
      })
      return
    }

    if (e.detail.userInfo) {
      // 保留用户选择的头像和输入的昵称
      const userInfo = {
        ...e.detail.userInfo,
        avatarUrl: this.data.userInfo.avatarUrl,
        nickName: this.data.userInfo.nickName
      }
      this.setData({
        userInfo,
        hasUserInfo: true
      })
      this.handleLogin(userInfo)
    }
  },

  handleLogin(userInfo) {
    wx.showLoading({
      title: '登录中...'
    })

    // 上传头像到云存储（如果不是默认头像）
    const uploadAvatar = () => {
      return new Promise((resolve, reject) => {
        if (userInfo.avatarUrl === defaultAvatarUrl || userInfo.avatarUrl.startsWith('cloud://')) {
          resolve(userInfo.avatarUrl)
          return
        }

        const cloudPath = `avatars/${userInfo.openid}-${Date.now()}.jpg`
        wx.cloud.uploadFile({
          cloudPath,
          filePath: userInfo.avatarUrl,
          success: res => resolve(res.fileID),
          fail: err => {
            console.error('上传头像失败：', err)
            resolve(defaultAvatarUrl)
          }
        })
      })
    }

    // 上传头像并保存用户信息
    uploadAvatar()
      .then(avatarFileID => {
        // 更新头像地址
        userInfo.avatarUrl = avatarFileID

        // 存储完整的用户信息
        wx.setStorageSync('userInfo', userInfo)
        
        wx.hideLoading()
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 2000
        })

        // 延迟跳转，让用户看到成功提示
        setTimeout(() => {
          wx.switchTab({
            url: '/pages/index/index'
          })
        }, 1500)
      })
      .catch(err => {
        console.error('登录过程出错：', err)
        wx.hideLoading()
        wx.showToast({
          title: '登录失败，请重试',
          icon: 'none',
          duration: 2000
        })
      })
  }
})